package com.zmn.brs.admin.controller.threshold;

import com.zmn.brs.common.constant.RedisKeyConst;
import com.zmn.brs.model.entity.rule.AlarmRule;
import com.zmn.brs.model.entity.threshold.Threshold;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.plat.common.dictionary.StatusEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述： 阈值规则
 * @author chongw
 * @since 2021-07-05 17:05:29
 */
@RestController
@RequestMapping("/brs/rule/threshold/")
public class ThresholdModifyController extends ThresholdBaseController {

    @Resource
    RedisTemplate<String, Integer> redisTemplate;

    /**
     * 启用规则
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("enable")
    public ResponseDTO enable(@RequestParam(value = "ids") List<Integer> ids){
        if(ids.isEmpty()){
            return ResponseDTO.fail("请选择需要启用的规则！");
        }
        //批量修改阈值规则状态
        Integer flag = this.modifyStatus(ids,StatusEnum.ENABLE.getCode());
        if(flag > 0){
            return ResponseDTO.success(null,"规则启用成功！");
        }
        return ResponseDTO.fail("规则启用失败！");
    }

    /**
     * 停用规则
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping("disable")
    public ResponseDTO disable(@RequestParam(value = "ids") List<Integer> ids){
        if(ids.isEmpty()){
            return ResponseDTO.fail("请选择需要停用的规则！");
        }
        //批量修改阈值规则状态
        Integer flag = this.modifyStatus(ids,StatusEnum.DISABLE.getCode());
        if(flag > 0){
            return ResponseDTO.success(null,"规则停用成功！");
        }
        return ResponseDTO.fail("规则停用失败！");
    }

    /**
     * 修改规则状态
     * @param thresholdIdList
     * @param status
     * @return
     */
    private Integer modifyStatus(List<Integer> thresholdIdList,Integer status){
        //设置需要修改的属性值
        List<Threshold> thresholdList = thresholdIdList.stream().map(o -> {
            Threshold threshold = thresholdService.findById(o);

            threshold.setStatus(status);
            threshold.setUpdater(super.getMcStaffName());
            threshold.setUpdateTime(DateUtil.getNow());
            return threshold;
        }).collect(Collectors.toList());

        Integer flag = thresholdService.updateBatchByKey(thresholdList);
        if(flag > 0){
            thresholdIdList.stream().forEach(o -> {
                String redisKey = RedisKeyConst.getStatusRedisKey(RedisKeyConst.THRESHOLD_STATUS_REDIS_KEY, o);
                redisTemplate.opsForValue().set(redisKey, status);
            });
        }
        return flag;
    }
}
